const express = require("express");
const mysql = require("mysql");
const app = express();
const cors = require("cors");
const ds = require("querystring");

app.use(express.urlencoded({ extended: false }));
app.use(cors());

const db = mysql.createPool({
  host: "127.0.0.1",
  user: "zhumingyu",
  password: "KwmJsjzeYPxbwd6y",
  database: "zhumingyu",
});

//获取
app.get("/api/get", (req, res) => {
  const sql = "select * from booklist";
  db.query(sql, (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});
//添加
app.post("/api/add", (req, res) => {
  const body = req.body;
  const sql = "insert into booklist (bookname,author,price) values (?,?,?)";
  db.query(sql, [body.bookname, body.author, body.price], (err, result) => {
    if (err) {
      console.log(err);
    } else {
      if (result.affectedRows === 1) {
        res.send({ code: 200, msg: "添加成功" });
      }
    }
  });
});
//删除
app.post("/api/delete", (req, res) => {
  const body = req.body;
  const sql = "delete from booklist where id=?";
  db.query(sql, [body.id], (err, result) => {
    if (err) {
      console.log(err);
    } else {
      if (result.affectedRows === 1) {
        res.send({ code: 200, msg: "删除成功" });
      }
    }
  });
});
//修改
app.post("/api/update", (req, res) => {
  const body = req.body;
  const sql = "update booklist set bookname=?,author=?,price=? where id=?";
  db.query(
    sql,
    [body.bookname, body.author, body.price, body.id],
    (err, result) => {
      if (err) {
        console.log(err);
      } else {
        if (result.affectedRows === 1) {
          res.send({ code: 200, msg: "修改成功" });
        }
      }
    }
  );
});
app.listen(3000, () => console.log("3000"));
